package com.tledu.ssm.controller;

import com.sun.javafx.scene.shape.PathUtils;
import com.tledu.ssm.core.AjaxResult;
import com.tledu.ssm.core.constants.ErrorCodeConstants;
import com.tledu.ssm.core.constants.UploadConstants;
import com.tledu.ssm.core.exception.LoginException;
import com.tledu.ssm.model.User;
import com.tledu.ssm.service.IUserService;
import lombok.AllArgsConstructor;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;

/**
 * @author cyrus
 */
@Controller
@RequestMapping("/user")
@AllArgsConstructor
public class UserController {

    private IUserService userService;

    @ResponseBody
    @RequestMapping("/selectById/{id}")
    public User selectById(@PathVariable Integer id) {
        return userService.selectById(id);
    }

    @RequestMapping("/list")
    public String userList(Model model) {
        model.addAttribute("list", userService.list());
        return "user/user-list";
    }

    @PostMapping("/upload/avatar")
    @ResponseBody
    public AjaxResult<String> uploadAvatar(MultipartFile file, HttpServletRequest request) {
        System.out.println(file.getSize());
        // 可以把这个file保存到服务器上
        if (file.isEmpty()) {
            return new AjaxResult<String>("请选择文件", ErrorCodeConstants.FILE_NOT_EXIST, null);
        }
        // 用户选择了文件
        // 得到tomcat的文件地址
//        String realPath = request.getServletContext().getRealPath(UploadConstants.AVATAR_UPLOAD_PATH);
        // 最终上传的文件的位置
        String finalPath = System.currentTimeMillis() + file.getOriginalFilename();
        // 目标文件，我们要流写到这个file里
        File finalFile = new File(UploadConstants.UPLOAD_FILE + File.separator + finalPath);

        try {
            FileUtils.copyInputStreamToFile(file.getInputStream(), finalFile);
//            file.transferTo(finalFile);
            // 请求成功
            // 返回文件路径
            return new AjaxResult<>("上传成功", "/upload" + "/" + finalPath);
        } catch (IOException e) {
            e.printStackTrace();
            //请求失败
            return new AjaxResult<String>("上传失败" + e.getMessage(), ErrorCodeConstants.FILE_NOT_EXIST, null);
        }
    }

    @RequestMapping("/edit")
    public String edit() {
        return "/user/user-edit";
    }

    @RequestMapping("/login")
    public String login(HttpSession session, String username, String password, Model model) throws LoginException {
        User user = null;
        user = userService.login(username, password);
        // 记录登录状态
        session.setAttribute("loginUser", user);
//        return "user/user-list";
        return "redirect:/user/list";
//        try {
//            user = userService.login(username, password);
//            // 记录登录状态
//            session.setAttribute("loginUser", user);
////        return "user/user-list";
//            return "redirect:/user/list";
//        } catch (LoginException e) {
//            e.printStackTrace();
//            model.addAttribute("msg", e.getMessage());
//            return "error";
//        }
    }

//    @ExceptionHandler(value = {LoginException.class, NullPointerException.class})
//    public String handleLoginError(LoginException e, Model model) {
//        model.addAttribute("msg", e.getMessage());
//        return "error";
//    }
//
//    @ExceptionHandler(value = {Exception.class})
//    public String handleError(Exception e, Model model) {
//        model.addAttribute("msg", e.getMessage());
//        return "error";
//    }
}
